/** 定义新闻相关接口 */
const express = require("express");
const router = express.Router();
const Joi = require("joi");
const Response = require("../utils/Response");

// 引入mysql连接池
const pool = require("../utils/pool");


/** 类型查询新闻列表（分页） */
router.get("/news/type", async (req, res) => {
  // 获取请求参数 get请求的参数封装在req.query中
  let { type, page, pagesize } = req.query;
  //TODO 服务端表单验证  如果验证通过那么继续后续业务  如果验证不通过，则直接返回参数异常
  let schema = Joi.object({
    type: Joi.string().required(), //必填
    page: Joi.number().required(), // page必须是字符串，必填
    pagesize: Joi.number().integer().required(), // pagesize必须是不大于100的数字，必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    console.log(error);
    res.send(Response.error(400, error));
    return;
  }
  let startIndex = (page - 1) * 8;
  let size = parseInt(pagesize);
  console.log(req.query);

  let allCount = await new Promise(resolve => {
    pool.query(
      "select count(*) from news where type=?",
      [type],
      (error, result) => {
        if (error) {
          res.send(Response.error(500, error));
          throw error;
        }
        resolve(result[0]["count(*)"]);
      }
    );
  });
  let sql = "select * from news where type = ? limit ?,?";
  pool.query(sql, [type, startIndex, size], (error, result) => {
    if (error) {
      res.send(Response.error(500, error));
      throw error;
    }
    // 将结果封装，返回给客户端
    // console.log(result,'================')
    let obj = Response.ok(result);
    obj.pages = Math.ceil(allCount / pagesize);
    obj.total = allCount;
    res.send(obj);
  });
});

/** id查询新闻消息 */
router.get("/news/eid", (req, res) => {
  let { eid } = req.query;
  let schema = Joi.object({
    eid: Joi.number().required(),
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    console.log(error);
    res.send(Response.error(400, error));
    return;
  }

  pool.query("select * from news where eid=?", [eid], (error, result) => {
    if (error) {
      res.send(Response(500, error));
      throw error;
    }
    res.send(Response.ok(result));
  });
});

/** 随机生成新闻 */
router.get("/news", (req, res) => {
  let { pagesize } = req.query;
  let schema = Joi.object({
    pagesize: Joi.number().required(),
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    console.log(error);
    res.send(Response.error(400, error));
    return;
  }
  console.log(pagesize);
  const sql = `SELECT title FROM news ORDER BY RAND() LIMIT ${pagesize}`
  pool.query(sql,(error,result)=>{
    if(error){
      res.send(Response.error(500, error));
      throw error;
    }
    res.send(Response.ok(result))
  });
});

// 将router对象导出
module.exports = router;
